//
//  PPPetLoveTableViewController.m
//  pet
//
//  Created by 陈无忌 on 12/22/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPPetLoveTableViewController.h"
#import "PPPetDetailTableViewController.h"
#import "ChatViewController.h"
#import "PPPetLoveCell.h"

#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"
#import "PPPetLove.h"

#import "PPConversation.h"


@interface PPPetLoveTableViewController ()

@property (nonatomic, weak) PPSystemConfiguraton *config;
@property (nonatomic, strong) NSMutableArray *petLoveArray;
@property (strong, nonatomic) UIAlertView *applyAlertView;
@property (strong ,nonatomic) PPPetLove *selectPetLove;
@property (nonatomic) BOOL isRefresh;

@end

@implementation PPPetLoveTableViewController

- (UIAlertView *)applyAlertView
{
    if (!_applyAlertView) {
        _applyAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"跟ta打个招呼吧~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_applyAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    }
    return _applyAlertView;
}

- (NSMutableArray *)petLoveArray{
    if (!_petLoveArray) {
        _petLoveArray = [NSMutableArray array];
    }
    return _petLoveArray;
}

- (PPSystemConfiguraton *)config{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getList];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(filtPetLove:) name:@"filtPetLove" object:nil];
    
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"正在刷新"];
    self.isRefresh = NO;
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:self.refreshControl];

}

- (void)refreshTableView{
    self.isRefresh = YES;
    [self getList];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)filtPetLove:(NSNotification *)notification
{
    NSDictionary *params = [notification userInfo];
    NSString *url = [PPAPIList getAPIList].PPQueryPetLoveByCondition;
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            [self.petLoveArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *infoList = resultMap[@"info"];
            NSMutableArray *resultList = [PPPetLove arrayOfModelsFromDictionaries:infoList];
            NSArray* sorte = [resultList sortedArrayUsingComparator:^NSComparisonResult(PPPetLove *love1, PPPetLove* love2){
                double distance1 = [love1.user distance];
                double distance2 = [love2.user distance];
                if(distance1 < distance2) {
                    return (NSComparisonResult)NSOrderedAscending;
                }else {
                    return (NSComparisonResult)NSOrderedDescending;
                }
            }];
            NSMutableArray *resultArray = [[NSMutableArray alloc] initWithArray:sorte];
            self.petLoveArray = [resultArray mutableCopy];
            [self.tableView reloadData];
        }else{
            [PPHUD hudShowWithString:@"没有获取到信息" andView:self.view];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];

}

- (void)getList
{
    NSString *url = [PPAPIList getAPIList].PPQueryPetLoveDefault;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            [self.petLoveArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *infoList = resultMap[@"info"];
            NSMutableArray *resultList = [PPPetLove arrayOfModelsFromDictionaries:infoList];
            NSArray* sorte = [resultList sortedArrayUsingComparator:^NSComparisonResult(PPPetLove *love1, PPPetLove* love2){
                double distance1 = [love1.user distance];
                double distance2 = [love2.user distance];
                if(distance1 < distance2) {
                    return (NSComparisonResult)NSOrderedAscending;
                }else {
                    return (NSComparisonResult)NSOrderedDescending;
                }
            }];
            NSMutableArray *resultArray = [[NSMutableArray alloc] initWithArray:sorte];
            self.petLoveArray = [resultArray mutableCopy];
            [self.tableView reloadData];
        }else{
            [PPHUD hudShowWithString:@"没有获取到信息" andView:self.view];
        }
        if (self.isRefresh) {
            self.isRefresh = NO;
             [self.refreshControl endRefreshing];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        if (self.isRefresh) {
            self.isRefresh = NO;
            [self.refreshControl endRefreshing];
        }
    }];
}

- (BOOL)checkFriend:(PPUserInfo *)targetUser
{
    for (PPUserInfo *user in self.config.friendArray) {
        if (user.id == targetUser.id) {
            return YES;
        }
    }
    return NO;
}


- (void)fastPack:(UIButton *)sender{
    PPPetLove *petLove = [self.petLoveArray objectAtIndex:sender.tag];
    self.selectPetLove = petLove;
    if ([self checkFriend:petLove.user]) {
        //如果是好友 直接去聊天页面
        NSString *url = [PPAPIList getAPIList].PPQueryConversationByTargetId;
        NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(petLove.user.id)};
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                //查询成功 直接得到会话传入
                NSError *err = nil;
                NSDictionary *resultMap = responseObject[@"resultMap"];
                NSDictionary *conversationDic = resultMap[@"conversation"];
                PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:[NSNumber numberWithInt:conversation.isGroup].boolValue];
                
                [conversation.conversation markMessagesAsRead:YES];
                ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
                
                targetVC.myConversation = conversation;
                targetVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:targetVC animated:YES];
                
                
            }else{
                [PPHUD hudShowWithString:@"会话获取失败" andView:self.view];
                //查询失败
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        }];
        
    }else{
        //不是好友 先发送好友请求
        [self.applyAlertView textFieldAtIndex:0].text = [NSString stringWithFormat:@"我是%@,我的宝宝想跟你的宝宝配种",self.config.userInfo.userName];
        [self.applyAlertView show];
    }

    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView isEqual:self.applyAlertView]) {
        UITextField *messageTextField = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            NSString *url = [PPAPIList getAPIList].PPSendRequest;
            NSDictionary *params = @{@"sendUserId":@(self.config.userInfo.id),@"targetUserId":@(self.selectPetLove.user.id),@"message":messageTextField.text};
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber *processResult = responseObject[@"processResult"];
                if (processResult.boolValue) {
                    [PPHUD hudShowWithString:@"请求已发送" andView:self.view];
                }else{
                    [PPHUD hudShowWithString:@"请求发送失败" andView:self.view];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [PPHUD hudShowWithString:@"网络错误" andView:self.view];
            }];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.petLoveArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPPetLoveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"petLoveCell"];
    PPPetLove *petLove = [self.petLoveArray objectAtIndex:indexPath.row];
    
    [cell.petAvatar setImageWithURL:[PPImageUrl getImageUrlOriginal:petLove.pet.petAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    cell.nameLabel.text = petLove.pet.petName;
    [cell.nameLabel sizeToFit];
    cell.sexImageView.frame = CGRectMake(cell.nameLabel.frame.size.width + cell.nameLabel.frame.origin.x + 5, 23, 15, 15);
    
    double distance = petLove.user.distance;
    if (distance < 1) {
        distance = distance * 1000;
        cell.detailLabel.text = [NSString stringWithFormat:@"距离:%.0f米",distance];
    }else{
        cell.detailLabel.text = [NSString stringWithFormat:@"距离:%.1f千米",distance];
    }
    
    switch (petLove.pet.petGender) {
        case 0:
            [cell.sexImageView setImage:[UIImage imageNamed:@"male"]];
            break;
        case 1:
            [cell.sexImageView setImage:[UIImage imageNamed:@"female"]];
            break;
            
        default:
            break;
    }
    
    
    [cell.fastPackButton addTarget:self action:@selector(fastPack:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.fastPackButton.tag = indexPath.row;
    // Configure the cell...
    
    return cell;
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetLove *petlove = [self.petLoveArray objectAtIndex:indexPath.row];
    PPPetInfo *pet = petlove.pet;
    PPPetDetailTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPetDetailTableViewController"];
    targetVC.pet = pet;
    [self.navigationController pushViewController:targetVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
